package com.dbh.algorithm;



import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *  生产者
 *
 * @author dongbanghui
 * @date 2018/06/22
 */
public class Producer implements Runnable {

    private volatile boolean isRunnning = true;

    /**
     *  内存缓冲区
     */
    private BlockingQueue<PCData> queue;

    /**
     * 总数，原子操作
     */
    private static AtomicInteger count = new AtomicInteger();

    private static final int SLEEPTIME = 1000;

    public Producer(BlockingQueue<PCData> queue){
        this.queue = queue;
    }


    @Override
    public void run() {
        PCData data;
        Random r = new Random();

        System.out.println("start producer id=" + Thread.currentThread().getId());

        try {
            while(isRunnning){
                Thread.sleep(r.nextInt(SLEEPTIME));
                //构造任务数据
                data = new PCData(count.incrementAndGet());
                System.out.println(data + " is put into queue");
                //提交任务到缓冲区
                if(!queue.offer(data, 2, TimeUnit.SECONDS)){
                    System.out.println("failed to put data:" + data);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }

    public void stop(){
        isRunnning = false;
    }
}
